let CODE;

layui.use(['upload', 'layer'], function () {
    let upload = layui.upload,
        layer = layui.layer;
    layui.layer.load(0, {shade: [0.5, '#fff']});
    queryInfo();

    /*换绑邮箱账号*/
    $("#updateEmailBtn").click(function () {
        layer.prompt({title: '输入账号密码继续操作', formType: 1}, function (pass, index) {
            layer.close(index);
            let url;
            if (ROLE === '1') {
                url = '/stuLogin';
            } else if (ROLE === '2') {
                url = '/teacherLogin';

            } else if (ROLE === '3') {
                url = '/adminLogin';
            } else {
                layui.layer.alert('出错啦!');
            }
            let loadPage = layui.layer.load(0, {shade: [0.5, '#fff']});
            $.ajax({
                url: url,
                type: 'post',
                data: {
                    userName: USERNAME,
                    password: pass
                },
                dataType: 'json',
                success: function (data) {  //调用接口成功
                    layui.layer.close(loadPage);
                    if (data === 1001 || data === '1001') {
                        openSetEmail();
                    } else if (data === 1002 || data === '1002') {
                        layui.layer.msg('密码错误', {offset: '300px', time: 2500, anim: 6});
                    } else {
                        layui.layer.msg('出错了', {offset: '300px', time: 2500, anim: 6});
                    }
                },
                error: function () {  //接口错误
                    layui.layer.close(loadPage);
                    layui.layer.alert('出错啦  (｡•́︿•̀｡)');
                }
            });


        });
    });

    function openSetEmail() {
        layer.open({
            type: 1
            , offset: 10
            , skin: 'layui-layer-rim'
            , area: ['1140px', '780px']
            , content: $("#setEmail")
            , title: '邮箱设置'
            , fixed: false
            , success: function (layero) {
                let mask = $(".layui-layer-shade");
                mask.appendTo(layero.parent());
            }
            , end: function () {
                $("#setEmail").css("display", 'none');
            }
        });
    }


    /*修改电子签名*/
    $("#signature-btn").click(function () {
        layer.open({
            type: 1
            , offset: 100
            , skin: 'layui-layer-rim'
            , area: ['400px', '430px']
            , content: $("#upload-img")
            , title: '上传电子签名'
            , success: function (layero) {
                let mask = $(".layui-layer-shade");
                mask.appendTo(layero.parent());
            }
            , end: function () {
                $("#upload-img").css("display", 'none');
            }
        });

        imgUpload();

    });

    /*上传图片容器初始化*/
    function imgUpload() {
        let uploadInst = upload.render({
            elem: '#test-upload-normal'
            , url: '/upload/'
            , accept: 'images'
            , size: 1024 * 5 //限制文件大小，单位 KB
            , acceptMime: 'image/*'
            , auto: false
            , bindAction: '#upload-normal'
            , choose: function (obj) {
                //将每次选择的文件追加到文件队列
                // let files = obj.pushFile();

                //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
                obj.preview(function (index, file, result) {
                    console.log(index); //得到文件索引
                    console.log(file); //得到文件对象
                    console.log(result); //得到文件base64编码，比如图片
                    //obj.resetFile(index, file, '123.jpg'); //重命名文件名，layui 2.3.0 开始新增

                    //这里还可以做一些 append 文件列表 DOM 的操作
                    $('#test-upload-normal-img').attr('src', result); //图片链接（base64）
                    //obj.upload(index, file); //对上传失败的单个文件重新上传，一般在某个事件中使用
                    //delete files[index]; //删除列表中对应的文件，一般在某个事件中使用
                });
            }

            , done: function (res) {
                //如果上传失败
                if (res.code > 0) {
                    return layer.msg('上传失败', {offset: '250px', time: 1500, anim: 6, area: ['200px', '50px']});
                } else {
                    return layer.msg('上传成功', {offset: '250px', time: 1500, anim: 6, area: ['200px', '50px']});
                }
            }
            , error: function () {
                //演示失败状态，并实现重传
                let demoText = $('#test-upload-demoText');
                demoText.html('<span style="color: #FF5722;padding: 5px">上传失败</span><br><a class="layui-btn layui-btn-mini demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
        });

    }

    layui.layer.closeAll('loading');


    //更新邮箱
    $("#updateEmail").click(function () {
        let newEmail = $("#setEmailBox").val().trim();
        let oldEmail = $("#email").html().trim();
        if (newEmail === oldEmail) {
            layer.msg('修改成功', {offset: '250px', time: 1500});
            return false;
        }
        //验证邮箱的合法性
        if (/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(newEmail)) {
            let loadPage = layui.layer.load(0, {shade: [0.5, '#fff']});
            $.ajax({
                url: '/updateUserEmail',
                type: 'post',
                data: {
                    userName: USERNAME,
                    email: newEmail,
                    role: ROLE
                },
                dataType: 'json',
                success: function (data) {  //调用接口成功
                    updateSuccess(data, loadPage);
                },
                error: function () {  //接口错误
                    layui.layer.close(loadPage);
                    layui.layer.alert('出错啦  (｡•́︿•̀｡)');
                }
            });
        } else {
            layer.msg('请输入正确的邮箱', {offset: '250px', time: 1500, anim: 6});
        }
    });


    //更新邮箱的授权码
    $("#updateEmailCode").click(function () {
        let newEmailCode = $("#setEmailCode").val().trim();
        if (newEmailCode === CODE) {
            layer.msg('修改成功', {offset: '250px', time: 1500});
            return false;
        }
        if (newEmailCode.length !== 16) {
            layer.msg('请输入16位授权码', {offset: '250px', time: 1500});
            return false;
        }
        let loadPage = layui.layer.load(0, {shade: [0.5, '#fff']});
        $.ajax({
            url: '/updateEmailCode',
            type: 'post',
            data: {
                userName: USERNAME,
                emailCode: newEmailCode,
                role: ROLE
            },
            dataType: 'json',
            success: function (data) {  //调用接口成功
                updateSuccess(data, loadPage);
            },
            error: function () {  //接口错误
                layui.layer.close(loadPage);
                layui.layer.alert('出错啦  (｡•́︿•̀｡)');
            }
        });

    });


    function updateSuccess(data, loadPage) {
        layui.layer.close(loadPage);
        if (data === true || data === 'true') {
            layer.closeAll('page');
            queryInfo();
            layer.msg('修改成功', {offset: '250px', time: 1500});
        } else {
            layui.layer.msg('修改失败', {offset: '300px', time: 2500, anim: 6});
        }
    }


});


//设置个人信息
function queryInfo() {
    let url = '/getInfo';
    let param = {userName: USERNAME, role: ROLE};
    $.get(url, param, function (data) {
        setInfo(data);
    }, 'json');
}


function setInfo(data) {
    if (ROLE === '1') {
        $("#NO").html(data.sNO);
        $("#name").html(data.name);
        $("#sex").html(data.sex);
        $("#college").html(data.collName);
        $("#major").html(data.majorName);
        $("#grade").html(data.classes);
        $("#tel").html(data.tel);
        $("#email").html(data.email);
        $("#signature").attr('src', 'img/signature.png');
        $("#setEmailBox").val(data.email);
        $("#setEmailCode").val(data.emailCode);
        CODE = data.emailCode;
    } else if (ROLE === '2') {
        $("#NO").html(data.tNO);
        $("#name").html(data.name);
        $("#sex").html(data.sex);
        $("#college").html(data.collegeId);
        $("#major").html(data.department);
        $("#grade").html(data.post);
        $("#tel").html(data.tel);
        $("#email").html(data.email);
        $("#signature").attr('src', 'img/signature.png');
        $("#setEmailBox").val(data.email);
        $("#setEmailCode").val(data.emailCode);
        CODE = data.emailCode;
    } else if (ROLE === '3') {
        $("#NO").html(data.adminName);
        $("#name").html(data.realName);
        // $("#tel").html(data.tel);
        $("#email").html(data.adminEmail);
        $("#signature").attr('src', 'img/signature.png');
        $("#setEmailBox").val(data.adminEmail);
        $("#setEmailCode").val(data.emailCode);
        CODE = data.emailCode;
    }

}


/*修改密码*/
function updatePass() {
    let pass = $("#password").val();
    let oldPass = $("#oldPass").val();

    if (!checkPassRes()) {
        layer.msg('密码不符合要求，请按要求设置', {offset: '250px', time: 1500, anim: 6});
        return false;
    }
    /*发送异步请求*/
    let loadPage = layui.layer.load(0, {shade: [0.5, '#fff']});
    $.ajax({
        url: "/updatePass",
        type: 'post',
        data: {
            role: ROLE, oldPass: oldPass, newPass: pass, userName: USERNAME
        },
        dataType: 'json',
        success: function (data) {  //调用接口成功
            layui.layer.close(loadPage);
            if (data === 1001 || data === '1001') {
                layui.layer.msg('修改密码成功!');
            } else if (data === 1002 || data === '1002') {
                layui.layer.msg('原密码错误!');
                $("#password").val("");
                $("#oldPass").val("");
                $("#again").val("");
            } else {
                layui.layer.msg('修改失败密码失败!');
            }
        },
        error: function () {  //接口错误
            layui.layer.close(loadPage);
            layui.layer.alert('服务器出错啦,请稍后再试！');
        }
    });
    return false;
}


/*检查新密码*/
function checkPassRes() {
    let userPass = $("#password").val();
    if (userPass.length === 0) {
        console.log(userPass);
        let msg = '6到16位字符,同时包含数字和大小写字母';
        $("#show-msg-pass").html(msg).css("color", "#9F9F9F");
        return false;
    } else if (userPass.length <= 6 || userPass.length >= 16) {
        let msg = '<i class="layui-icon layui-icon-tips" style="color: red;font-size: 15px"> </i>' +
            '<span style="color: red">密码的长度再6~10之间</span>';
        $("#show-msg-pass").html(msg);
        return false;
    } else {
        let regex1 = /[a-z]/;
        let regex2 = /[A-Z]/;
        let regex3 = /[1-9]/;
        if (regex1.test(userPass) && regex2.test(userPass) && regex3.test(userPass)) {
            let msg = '<i class="layui-icon layui-icon-ok-circle" style="color: green;font-size: 15px"> </i>' +
                '<span style="color: green">密码符合要求,可用使用该密码</span>';
            $("#show-msg-pass").html(msg);
            return true;
        } else {
            let msg = '<i class="layui-icon layui-icon-tips" style="color: red;font-size: 15px"> </i>' +
                '<span style="color: red">密码必须同时包含数字和大小写字母</span>';
            $("#show-msg-pass").html(msg);
            return false;
        }
    }
}

/*检查两次密码是否一致*/
function checkPassAgain() {
    let userPass = $("#password").val();
    let userPass1 = $("#again").val();
    if (userPass1.length === 0) {
        let msg = '再次输入账号密码';
        $("#show-msg-pass-again").html(msg).css("color", "#9F9F9F");
        return false;
    }
    if (userPass === userPass1) {
        let msg = '<i class="layui-icon layui-icon-ok-circle" style="color: green;font-size: 15px"> </i>' +
            '<span style="color: green">两次输入密码一致';
        $("#show-msg-pass-again").html(msg);
        return true;
    } else {
        let msg = '<i class="layui-icon layui-icon-tips" style="color: red;font-size: 15px"> </i>' +
            '<span style="color: red">两次输入密码不一致,请检查</span>';
        $("#show-msg-pass-again").html(msg);
        return false;
    }

}
